// 登录相关路由
const express = require('express')
const router = express.Router()
const { RES_CODE } = require('../utils/contants')
const verifyToken = require('../middlewares/verifyToken')
const { generateToken } = require('../utils/tokenUtils')
const md5 = require('md5')
const UserModel = require('../db/models/UserModel')

// 登录
router.post('/login', async (req, res) => {
    const { username, pwd } = req.body
    // 查找数据库中有没有该用户
    try {
        let user = await UserModel.findOne({ username, pwd: md5(pwd) })
        console.log(user)
        if (user) {
            // 生成token
            const token = generateToken(user['_id'])
            console.log(token)
            // 响应token
            res.json({
                code: RES_CODE.SUCCESS,
                msg: '登录成功',
                data: {
                    token,
                    user
                }
            })
        } else {
            res.json({
                code: RES_CODE.NEED_LOGIN,
                msg: '用户名或密码错误'
            })
        }
    } catch (err) {
        res.statusCode = 500
        res.json({
            code: RES_CODE.ERROR,
            msg: '服务器错误'
        })
    }
})

// 获取用户信息
router.get('/info', verifyToken, async (req, res) => {
    const userId = req.userId
    const user = await UserModel.findById(userId)
    res.json({
        code: RES_CODE.SUCCESS,
        data: {
            user
        }
    })
})

// 用户登出
router.get('/logout', verifyToken, async (req, res) => {
    // 返回成功
    res.json({
        code: RES_CODE.SUCCESS,
        msg: '登出成功'
    })
})

// 暴露
module.exports = router
